import { onMounted } from 'vue'

export const useScroll = scrollContainer => {
  const autoScroll = ref(true)
  let lastScrollTop = 0
  let time

  // 开启自动滚动
  const openAutoScroll = () => {
    autoScroll.value = true
    scrollToBottom()

    time = setInterval(() => {
      scrollToBottom()
    }, 1000)
  }

  // 关闭自动滚动
  const closeAutoScroll = () => {
    autoScroll.value = false
    clearInterval(time)
  }

  // 滚动到顶部
  const scrollToBottom = () => {
    if (!autoScroll.value) return
    if (!scrollContainer.value) return

    scrollContainer.value.scrollTo({
      top: scrollContainer.value.scrollHeight,
      behavior: 'smooth',
    })
  }

  const scroll = () => {
    const scrollTop = scrollContainer.value.scrollTop

    // 判断滚动方向
    if (scrollTop > lastScrollTop) {
      // 检查是否滚动到底部
      if (!autoScroll.value && isScrolledToBottom(scrollContainer.value)) openAutoScroll()
    } else if (scrollTop < lastScrollTop) {
      // 向上滚动
      if (autoScroll.value) closeAutoScroll()
    }

    // 更新上一次的滚动位置
    lastScrollTop = scrollTop
  }

  // window.addEventListener('scroll', scroll)

  onMounted(() => {
    scrollContainer.value.addEventListener('scroll', scroll)
  })

  onUnmounted(() => {
    scrollContainer.value.removeEventListener('scroll', scroll)
  })

  return {
    autoScroll,

    openAutoScroll,
    closeAutoScroll,

    scrollToBottom,
  }
}

function isScrolledToBottom(element, threshold = 50) {
  return element.scrollHeight - element.scrollTop - element.clientHeight <= threshold
}
